package com.weaver.qfengx.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weaver.qfengx.DaoUtils;
import org.apache.commons.compress.utils.Lists;
import weaver.soa.workflow.request.RequestInfo;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Objects;

/**
 * 基础JS Action 通过调用JS 执行一系列操作来实现动态变化
 */
public class BaseJsAction extends BaseAction {

    private String jsFilePath;
    private String jsExecFn = "execCode"; // 默认调用方法名

    public BaseJsAction() {
        setActionName("JS 动态执行Action");
    }

    public String getJsFilePath() {
        return jsFilePath;
    }

    public BaseJsAction setJsFilePath(String jsFilePath) {
        this.jsFilePath = jsFilePath;
        return this;
    }

    public String getJsExecFn() {
        return jsExecFn;
    }

    public BaseJsAction setJsExecFn(String jsExecFn) {
        this.jsExecFn = jsExecFn;
        return this;
    }

    @Override
    public void execCode(RequestInfo requestInfo) throws Exception {
        // 进一步封装流程相关信息, 以供JS 调取使用
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        // 过滤头尾两行
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(new File(jsFilePath))));
        StringBuilder stringBuilder = new StringBuilder();
        String temp = "";
        List<String> lineStrs = Lists.newArrayList();
        int lineSum = 0;
        while ((temp = reader.readLine()) != null) {
            // 过滤第一行
            lineStrs.add(temp);
        }
        for (int i = 1; i < lineStrs.size() - 1; i++) {
            stringBuilder.append(lineStrs.get(i));
            stringBuilder.append("\n");
        }
        engine.eval(stringBuilder.toString());
        if (engine instanceof Invocable) {
            Invocable in = (Invocable) engine;
            engine.put("mainTableMap", mainTableMap);
            String resJson = (String) in.invokeFunction(jsExecFn);
            JSONObject jsonObject = JSON.parseObject(resJson);
            isOk = jsonObject.getBoolean("isOk");
            message = jsonObject.getString("message");
        }
    }
}
